<template>
  <div class="detail-wrap">
    <div v-tit="'应用关联信息'">
      <GForm ref="detail1" :config="formConfig1" inline :rules="formRules" v-model="form"></GForm>
    </div>
    <div v-tit="'应用信息'">
      <GForm ref="detail2" :config="formConfig2" inline :rules="formRules" v-model="form" @handleInput="handleInput"></GForm>
    </div>
    <div v-tit="'应用环境信息'">
      <el-table :data="envList" border stripe :height="calcHeight(340)">
        <el-table-column v-for="col in baseColumns" :prop="col.prop" :key="col.prop" :label="col.label" align='center'>
          <template #header>
            <template v-if="col.input == 'action'">
              <el-button type="primary" @click="handleAddEnv">新增</el-button>
            </template>
            <template v-else-if="['aboveEnvironmentId','belowEnvironmentId'].includes(col.prop)">
              <span style="color:#409eff">*{{col.label}}</span>
            </template>
            <template v-else>
              <span>{{col.label}}</span>
            </template>
          </template>
          <template slot-scope="scope">
            <template v-if="col.input == 'select'">
              <el-select v-model="scope.row[col.prop]" placeholder="" clearable filterable>
                <el-option v-for="item in options.env" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </template>
            <template v-else-if="col.input == 'input'">
              <el-input v-model="scope.row[col.prop]" placeholder="" clearable></el-input>
            </template>
            <template v-else-if="col.input == 'action'">
              <template v-for="btn in col.btnConfig">
                <el-button :type="btn.type" :disabled="btn.disabled?btn.disabled(scope.row):false" :key="btn.invalid" @click="handleBtnAction(btn,scope)">{{btn.label}}</el-button>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-button type="primary" @click="handleConfirm()">确定</el-button>
      <el-button @click="$router.push('/app/relevance')">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'relevance',
  data() {
    return {
      relevanceId: null,
      form: {
        companyId: null,
        linkName: null,
        linkStatus: '50501',
        linkDesc: null,
        aboveCompanyId: null,
        aboveCompanyNo: null,
        aboveCompanyName: null,
        applicationStatus: null,
        aboveApplicationId: null,
        aboveApplicationNo: null,
        aboveApplicationName: null,
        belowCompanyId: null,
        belowCompanyNo: null,
        belowCompanyName: null,
        belowApplicationId: null,
        belowApplicationNo: null,
        belowApplicationName: null,
        items: []
      },
      envList: [],
      options: {
        company: [],
        env: [],
        app: [],
        status: []
      }
    }
  },
  computed: {
    baseColumns() {
      return [
        {
          label: '上位应用环境',
          prop: 'aboveEnvironmentId',
          input: 'select',
          // options: this.options.env
        },
        {
          label: '下位应用环境',
          prop: 'belowEnvironmentId',
          input: 'select',
          // options: this.options.env
        },
        {
          label: '备注',
          prop: 'remark',
          input: 'input'
        },
        {
          label: '操作',
          prop: 'action',
          input: 'action',
          btnConfig: [
            // {
            //   label: '保存',
            //   invalid: 'saveDetail',
            //   type: 'primary'
            //   // permi: ['timeTask:pause'],
            //   // disabled: data => data.triggerState != 'WAITING'
            // },
            {
              label: '删除',
              invalid: 'delete',
              type: 'warning'
              // permi: ['timeTask:pause'],
              // disabled: data => data.triggerState != 'WAITING'
            }
          ]
        }
      ]
    },
    formConfig1() {
      return [
        {
          prop: 'linkName',
          type: 'input',
          label: '关联名称',
          desc: '填写相关联应用的名称组合，比如: ERP-WMS'
        },
        {
          prop: 'linkStatus',
          label: '启用状态',
          type: 'select',
          options: this.options.status
        },
        {
          prop: 'linkDesc',
          type: 'textarea',
          label: '关联描述'
        }
      ]
    },
    formConfig2() {
      return [
        {
          prop: 'aboveCompanyName',
          label: '上位公司',
          type: 'input',
          disabled: true
        },
        {
          prop: 'belowCompanyName',
          label: '下位公司',
          type: 'input',
          disabled: true,
          break: true
        },
        {
          prop: 'aboveApplicationId',
          label: '上位应用',
          type: 'select',
          options: this.options.app
        },
        {
          prop: 'belowApplicationId',
          label: '下位应用',
          type: 'select',
          options: this.options.app
        }
      ]
    },
    formRules() {
      return {
        linkName: [
          {
            required: true,
            message: '请填写关联名称',
            trigger: 'blur'
          }
        ],
        linkStatus: [
          {
            required: true,
            message: '请选择启用状态',
            trigger: 'change'
          }
        ],
        aboveApplicationId: [
          {
            required: true,
            message: '请选择上位应用',
            trigger: 'change'
          }
        ],
        belowApplicationId: [
          {
            required: true,
            message: '请选择下位应用',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    async handleConfirm() {
      const promise1 = this.$refs.detail1.validate()
      const promise2 = this.$refs.detail2.validate()
      await Promise.all([promise1, promise2]).then(async valid => {
        const params = this._.cloneDeep(this.form)
        params.items = []
        for (let i = 0; i < this.envList.length; i++) {
          const envInfo = this.envList[i]
          if (!envInfo.aboveEnvironmentId) {
            return this.$message.error('请选择上位应用环境')
          }
          if (!envInfo.belowEnvironmentId) {
            return this.$message.error('请选择下位应用环境')
          }
          const aboveEnvObj = this.options.env.find(
            opt => opt.value == envInfo.aboveEnvironmentId
          )
          const {
            environmentName: aboveEnvironmentName,
            environmentNo: aboveEnvironmentNo
          } = aboveEnvObj
          const belowEnvObj = this.options.env.find(
            opt => opt.value == envInfo.belowEnvironmentId
          )
          const {
            environmentName: belowEnvironmentName,
            environmentNo: belowEnvironmentNo
          } = belowEnvObj
          params.items.push({
            ...envInfo,
            aboveEnvironmentName,
            aboveEnvironmentNo,
            belowEnvironmentName,
            belowEnvironmentNo
          })
        }

        let promise
        if (this.relevanceId) {
          params.items.forEach(i => (i.linkId = this.relevanceId))
          promise = this.$post(
            `/v1/plApplicationLink/editPlApplicationLink`,
            params
          )
        } else {
          promise = this.$post(
            `/v1/plApplicationLink/addPlApplicationLink`,
            params
          )
        }
        promise.then(res => {
          this.$message.success(res.returnMgr)
          this.$router.push("/app/relevance")
          // if (this.relevanceId) {
          //   this.getInfoById()
          // }
        })
      })
    },
    handleInput(prop, value, obj) {
      if (prop == 'aboveApplicationId') {
        this.form.aboveCompanyId = obj.companyId
        this.form.aboveApplicationName = obj.applicationName
        this.form.aboveApplicationNo = obj.applicationNo
        const aboveCompanyObj = this.options.company.find(
          opt => opt.value == obj.companyId
        )
        this.form.aboveCompanyName = aboveCompanyObj.companyName
        this.form.aboveCompanyNo = aboveCompanyObj.companyNo
      } else if (prop == 'belowApplicationId') {
        this.form.belowApplicationName = obj.applicationName
        this.form.belowApplicationNo = obj.applicationNo
        this.form.belowCompanyId = obj.companyId
        const belowCompanyObj = this.options.company.find(
          opt => opt.value == obj.companyId
        )
        this.form.belowCompanyName = belowCompanyObj.companyName
        this.form.belowCompanyNo = belowCompanyObj.companyNo
      }
    },
    handleAddEnv() {
      this.envList.push({
        aboveEnvironmentId: null,
        belowEnvironmentId: null,
        remark: null
      })
    },
    handleBtnAction(btn, scope) {
      const row = scope.row
      if (btn.invalid == 'saveDetail') {
        this.saveDetail(row)
      } else if (btn.invalid == 'delete') {
        this.del(row, scope.$index)
      }
    },
    saveDetail(data) {
      if (!data.aboveEnvironmentId) {
        return this.$message.error('请选择上位应用环境')
      }
      if (!data.belowEnvironmentId) {
        return this.$message.error('请选择下位应用环境')
      }
      const aboveObj = this.options.env.find(
        opt => opt.id == data.aboveEnvironmentId
      )
      const {
        environmentNo: aboveEnvironmentNo,
        environmentName: aboveEnvironmentName
      } = aboveObj
      const belowObj = this.options.env.find(
        opt => opt.id == data.belowEnvironmentId
      )
      const {
        environmentNo: belowEnvironmentNo,
        environmentName: belowEnvironmentName
      } = belowObj
      const params = {
        aboveEnvironmentNo,
        aboveEnvironmentName,
        belowEnvironmentNo,
        belowEnvironmentName,
        ...data
      }
      this.$post('/v1/plApplicationLink/addPlApplicationLinkDtl', params).then(
        res => {
          this.$message.success(res.returnMgr)
          this.envList[index] = res.data
        }
      )
    },
    del(data, index) {
      if (data.id) {
        this.$post(
          '/v1/plApplicationLink/deletePlApplicationLinkDtlById',
          data
        ).then(res => {
          this.$message.success(res.returnMgr)
          this.envList.splice(index, 1)
        })
      } else {
        this.envList.splice(index, 1)
      }
    },
    getOptions() {
      this.$get('/system/codeLookup/LinkStatus').then(res => {
        this.options.status = res.data.item.map(i => {
          i.label = i.description
          i.value = i.code
          return i
        })
      })
      this.$post('/v1/plApplication/selectPlApplicationList', {
        pageNum: 1,
        pageSize: 999,
        applicationStatus: '50301'
      }).then(res => {
        const data = res.data.page.records
        this.options.app = data.map(i => {
          i.label = i.applicationName
          i.value = i.id
          return i
        })
      })
      this.$post('/v1/edi/plCompany/selectPlCompany', {
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        const data = res.data.item
        this.options.company = data.map(i => {
          i.label = i.companyName
          i.value = i.id
          return i
        })
      })
      this.$post('/v1/plApplicationEnvironment/selectList', {
        pageNum: 1,
        pageSize: 999,
        environmentStatus: '50301'
      }).then(res => {
        const data = res.data.page.records
        console.log(data,'>>>>>');
        this.options.env = data.map(i => {
          i.label = i.environmentName
          i.value = i.id
          return i
        })
        this.$forceUpdate()
        console.log(this.options.env);
      })
    },
    getInfoById() {
      this.$post('/v1/plApplicationLink/selectPlApplicationLinkById', {
        id: this.relevanceId
      }).then(res => {
        const data = res.data
        this.form = data.item
      })
      this.$post('/v1/plApplicationLink/selectPlApplicationLinkDtlByLinkId', {
        linkId: this.relevanceId
      }).then(res => {
        const data = res.data.page
        this.envList = data.records||[]
      })
    }
  },
  mounted() {
    const query = this.$route.query
    if (query.id) {
      this.relevanceId = query.id
      this.getInfoById()
    }
    this.getOptions()
  }
}
</script>

<style lang="scss" scoped>
.detail-wrap {
  height: 100%;
  position: relative;
  .el-table {
    .el-select,
    .el-input {
      width: 100%;
    }
  }
  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    background: #f4f4f4;
    text-align: center;
    padding: 10px 0;
  }
}
</style>
